package ua.edu.nuos.jeetraining2012.cms.util.template;

import freemarker.core.Environment;
import freemarker.core.Macro;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Writer;
import java.util.Locale;

/**
 * Class for processing and rendering template
 */
public class TemplateRenderer {

    protected final Configuration cfg;
    protected final Logger logger = LoggerFactory.getLogger(getClass());


    public TemplateRenderer() {
        cfg = new Configuration();
        cfg.setEncoding(Locale.getDefault(), "UTF-8");
        cfg.setClassForTemplateLoading(getClass(), "/templates");
    }


    /**
     * Process template and write template body to {@link Writer}
     *
     * @param templateParam implementation of {@link Templatable} interface that provides template data to be processed.
     * @param out           Writer object to be written to
     * @return true if template was processed and output written successfully, false otherwise
     */
    public boolean process(Templatable templateParam, Writer out) {
        try {
            Template template = cfg.getTemplate(templateParam.getTemplateFilename());
            template.process(templateParam.getMap(), out);
        } catch (IOException | TemplateException e) {
            logger.error("Render template error. Template filename " + templateParam.getTemplateFilename(), e);
            return false;
        }
        return true;
    }
}
